# for each use

require "dbm"
require "00_common"

module UserActivityStat
  def self.file_has_handled?(db_name)
    handled_db_name = String.new(db_name)
    handled_db_name[/user/]= "activity"

    Common.file_exist?("./user_activity_stat", handled_db_name)
  end

  def self.build_user_activity_db(db_name)
    puts "now handling #{db_name}..."
    # db_name = file[0, file.length - 3]
    
    #
    # the new db
    #
    # db_new_name = file[0, file.length - 3]
    db_new_name = String.new(db_name)
    db_new_name[/user/] = "activity"     
    db_new = DBM.open db_new_name

    #
    # for each entry of the old db
    #
    db = DBM.open "./db_files/" + db_name
    db.each do |key, value|
      lines = value.split "$|$"

      timestamps = []
      cpayloads = []
      spayloads = []

      # go through each line
      lines.each do |line|
        fields = line.split "|"
        timestamps << (fields[LOCAL_TIME_STAMP].length == 0 ? "NULL" : fields[LOCAL_TIME_STAMP])
        cpayloads << (fields[CLIENT_PAYLOAD].length == 0 ? "NULL" : fields[CLIENT_PAYLOAD])
        spayloads << (fields[SERVER_PAYLOAD].length == 0 ? "NULL" : fields[SERVER_PAYLOAD])
      end

      db_new_value = "num||#{lines.size}" + "|||" + "timestamps||#{timestamps.join("|")}" + "|||" + "cpayloads||#{cpayloads.join("|")}" + "|||" + "spayloads||#{spayloads.join("|")}"

      db_new[key] = db_new_value
    end

    #
    # close all the db
    #
    db.close
    db_new.close

    #
    # move the new db
    #
    Common.move_file db_new_name + ".db", "./user_activity_stat"
  end # self.build_user_activity_db
end

begin

  db_list = Common.get_all_files "./db_files"
  puts "== the size of the file list is #{db_list.length}."

  db_list.each do |file|
    puts "to handle #{file}..."
    if UserActivityStat.file_has_handled? file
      puts "--> the file has been hanlded: " + file
    else
      UserActivityStat.build_user_activity_db(file[0, file.length - 3])
    end
  end
rescue Exception => e
  puts e.to_s	
end